package ws

import (
	"github.com/google/uuid"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"sync"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		// 允许所有的请求来源
		return true
	},
}

var connections sync.Map

func wsHandler(w http.ResponseWriter, r *http.Request) {
	// 将 HTTP 连接升级为 WebSocket 连接
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("升级连接失败:", err)
		return
	}
	defer conn.Close()
	connId := uuid.New()
	log.Printf("WS新客户端连接，分配ID：%s", connId)
	connections.Store(connId, conn)

	for {
		// 读取客户端发送的消息
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("读取消息失败:", err)
			connections.Delete(connId)
			break
		}

		// 打印消息到控制台
		log.Printf("收到消息: %d，消息内容：%s", messageType, message)
		//SendToAll(message)
	}
}

func Start(port string) {
	// 定义路由
	http.HandleFunc("/", wsHandler)

	// 启动 WebSocket 服务器
	log.Println("WebSocket 服务器启动，监听在 " + port + " 端口...")
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func SendToAll(message []byte) {
	// 将消息原样发送回客户端
	connections.Range(func(key, value interface{}) bool {
		value.(*websocket.Conn).WriteMessage(1, message)
		return true
	})
}
